package com.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.job.common.Constant;
import com.job.common.ResponseResult;
import com.job.common.asserts.MyAssert;
import com.job.common.converter.CorporationFieldConverter;
import com.job.common.converter.PositionFieldConverter;
import com.job.common.converter.StudentFieldConverter;
import com.job.common.enums.ResultCodeEnum;
import com.job.common.exception.ParameterIsNullException;
import com.job.controller.req.RecruitAddVO;
import com.job.controller.req.RecruitStudentReqVO;
import com.job.controller.resp.RecruitVO;
import com.job.dao.RecruitDao;
import com.job.mapper.*;
import com.job.pojo.*;
import com.job.pojo.vo.PositionVO;
import com.job.pojo.vo.StudentVO;
import com.job.service.RecruitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RecruitServiceImpl implements RecruitService , Constant {

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private HrMapper hrMapper;

    @Resource
    private PositionInfoMapper positionInfoMapper;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private RecruitDao recruitDao;

    @Resource
    private PositionFieldConverter positionFieldConverter;

    @Resource
    private StudentFieldConverter studentFieldConverter;

    @Resource
    private CorporationMapper corporationMapper;

    @Resource
    private CorporationFieldConverter corporationFieldConverter;




    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult<ResultCodeEnum> recruitAdd(RecruitAddVO recruitAddVO) throws ParameterIsNullException {
        MyAssert.objectParameterCheck(recruitAddVO);
        Integer hrId = recruitAddVO.getHrId();
        MyAssert.objectParameterCheck(recruitAddVO);

        Hr hr = hrMapper.selectById(hrId);
        Position position = PositionPoToVoConverter(recruitAddVO,hr);
        if (positionMapper.insert(position) < 1){
            throw new RuntimeException("插入失败");
        }

        PositionInfo positionInfo = new PositionInfo();
        positionInfo.setPositionId(position.getPositionId());
        positionInfo.setCity(recruitAddVO.getCity());
        positionInfo.setTitle(recruitAddVO.getTitle());
        positionInfo.setContext(recruitAddVO.getContext());
        if (positionInfoMapper.insert(positionInfo) < 1){
            throw new RuntimeException("插入失败");
        }
        return new ResponseResult<ResultCodeEnum>().success();
    }

    public Position PositionPoToVoConverter(RecruitAddVO recruitAddVO, Hr hr){
        Position position = new Position();
        position.setPosition(recruitAddVO.getPosition());
        position.setAward(recruitAddVO.getAward());
        position.setCreateTime(LocalDateTime.now());
        position.setHrId(recruitAddVO.getHrId());
        position.setSalaryStart(recruitAddVO.getSalaryStart());
        position.setSalaryEnd(recruitAddVO.getSalaryEnd());
        position.setXl(recruitAddVO.getXl());
        position.setCorporationId(hr.getCorporationId());
        return position;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult<ResultCodeEnum> recruitDelete(Integer positionId) {
        if (Objects.isNull(positionId)){
            log.info("参数为空");
            new ResponseResult<ResultCodeEnum>().fail(ResultCodeEnum.PARAMETER_IS_NULL_FAIL);
        }
        if (recruitDao.deletePositionInfo(positionId) || recruitDao.deletePosition(positionId)){
            throw new RuntimeException("删除失败");
        }

        return new ResponseResult<ResultCodeEnum>().success();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult<ResultCodeEnum> recruitUpdate(RecruitAddVO recruitAddVO) {
        if (Objects.isNull(recruitAddVO)){
            log.info("参数为空");
            throw new RuntimeException("参数为空");
        }
        Integer positionId = recruitAddVO.getPositionId();
        if (Objects.isNull(positionId)){
            log.info("参数为空");
            throw new RuntimeException("参数为空");
        }
        Position position = recruitDao.queryPosition(positionId);
        PositionInfo positionInfo = recruitDao.queryPositionInfo(positionId);
        if (Objects.isNull(position) || Objects.isNull(positionInfo)){
            log.info("职位不存在");
            throw new RuntimeException("职位不存在");
        }

        BeanUtils.copyProperties(recruitAddVO,position);
        BeanUtils.copyProperties(recruitAddVO,positionInfo);
        if (positionMapper.updateById(position) < 1 || positionInfoMapper.updateById(positionInfo) < 1){
            log.info("修改失败");
            throw new RuntimeException("修改失败");
        }
        return new ResponseResult<ResultCodeEnum>().success();
    }

    @Override
    public ResponseResult<IPage<Map<String,Object>>> recruitQuery(String hrId) throws ParameterIsNullException {
        List<Position> positions = recruitDao.queryPositionByHrId(hrId);
        Page<Map<String, Object>> positionPage = new Page<>();
        List<Map<String, Object>> list = new ArrayList<>();
        positions.forEach(position -> {
            //PositionInfo positionInfo = recruitDao.queryPositionInfo(position.getPositionId());
            HashMap<String, Object> map = new HashMap<>();
            PositionVO positionVO = positionFieldConverter.PositionPoToVoConverter(position);
            Corporation corporation = corporationMapper.selectById(positionVO.getCorporationId());
            if (!Objects.isNull(corporation)){
                map.put("corporation",corporationFieldConverter.corporationPoToVoConverter(corporation));
            }
            map.put("position",positionVO);
            list.add(map);
        });
        positionPage.setRecords(list);

        return new ResponseResult<IPage<Map<String,Object>>>().success(positionPage);
    }

    @Override
    public ResponseResult<Page<StudentVO>> studentList(RecruitStudentReqVO recruitStudentVO) {
        Page<StudentVO> studentPage = new Page<>();
        studentPage.setCurrent(recruitStudentVO.getCurrent());
        studentPage.setSize(recruitStudentVO.getSize());
        recruitStudentVO.setCurrent(recruitStudentVO.getSize() * (recruitStudentVO.getCurrent() - 1));
        if (Objects.isNull(recruitStudentVO)){
            log.info("参数为空");
            return new ResponseResult<Page<StudentVO>>().fail(ResultCodeEnum.FAIL);
        }

        List<Student> students = studentMapper.studentList(recruitStudentVO);
        Integer count = studentMapper.selectPageCount(recruitStudentVO);
        studentPage.setTotal(count);
        if (CollectionUtils.isEmpty(students)){
            log.info("没有找到符合的学生");
            return  new ResponseResult<Page<StudentVO>>().success(studentPage);
        }
        List<StudentVO> studentVOS = students.stream()
                .map(student -> studentFieldConverter.studentPoToVo(student)).collect(Collectors.toList());
        studentPage.setRecords(studentVOS);

        return new ResponseResult<Page<StudentVO>>().success(studentPage);
    }


    @Override
    public ResponseResult<List<RecruitVO>> mateRecruitQuery(String id) {
        LambdaQueryWrapper<Position> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Position::getHrId, id);
        List<Position> positions = positionMapper.selectList(wrapper);
        List<RecruitVO> collect = positions.stream().map(position -> {
            RecruitVO recruitVO = new RecruitVO();
            BeanUtils.copyProperties(position, recruitVO);
            return recruitVO;
        }).collect(Collectors.toList());
        return new ResponseResult<List<RecruitVO>>().success(collect);
    }
}
